package com.york.tinyrpc.protoss.loadbalancer;

import com.york.tinyrpc.protoss.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询模式
 * 适用于各个服务节点性能相近的情况
 */
public class RoundRobinLoadBalancer implements LoadBalancer {

    /**
     * 初始化当前轮询值，取模得到最终值
     */
    private final AtomicInteger currentCount = new AtomicInteger(0);

    /**
     * 获取目标服务
     *
     * @param requestParams 请求参数
     * @param serviceList   可选服务列表
     * @return
     */
    @Override
    public ServiceMetaInfo getTargetService(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceList) {
        if (serviceList.isEmpty()) {
            return null;
        }
        int size = serviceList.size();
        // 只有一个可选服务时直接用
        if (size == 1) {
            return serviceList.get(0);
        }

        // 轮询得到最终结果
        int targetIndex = currentCount.getAndIncrement() % size;
        return serviceList.get(targetIndex);
    }
}
